﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class CameraScreenLightRender : MonoBehaviour {

    public Shader ReplaceShader;
    public Shader BlurShader;

    private Material _blurMaterial;
    private Camera _screenLightCamera;

    private RenderTexture _screenLightRt;
    private RenderTexture _cameraRenderRt;


    void OnEnable()
    {       
        if (!_screenLightRt || !_cameraRenderRt)
        {

            int width = Screen.width;
            int height = Screen.height;
            
            _screenLightRt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
            _cameraRenderRt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
    
        }  
    }

    void OnDisable()
    {

        if (_screenLightRt)
        {
            _screenLightRt.Release();
            _screenLightRt = null;
        }
        if (_cameraRenderRt)
        {
            _cameraRenderRt.Release();
            _cameraRenderRt = null;
        }

    }

    //模糊半径
    public float BlurRadius = 1.0f;

    void LateUpdate()
    {
        CameraCopy();
        var last = _screenLightCamera.targetTexture;
        _screenLightCamera.targetTexture = _cameraRenderRt;
        _screenLightCamera.RenderWithShader(ReplaceShader, "QxLightingSprite");
       

        if (_blurMaterial)
        {                      
            _blurMaterial.SetFloat("_BlurRadius", BlurRadius);
            Graphics.Blit(_cameraRenderRt, _screenLightRt, _blurMaterial);     
        }

        Shader.SetGlobalTexture("_ScreenLightTex", _screenLightRt);
    }


    private void CameraCopy()
    {
        Camera camera = GetComponent<Camera>();

        if (!_screenLightCamera)
        {
            var childCameraTrans = transform.Find("ScreenLightCamera");
            if (childCameraTrans)
            {
                _screenLightCamera = childCameraTrans.GetComponent<Camera>();
            }

            if (!_screenLightCamera)
            {
                _screenLightCamera = new GameObject("ScreenLightCamera").AddComponent<Camera>();
                _screenLightCamera.transform.SetParent(transform);
            }
            _screenLightCamera.enabled = false;
        }

        if (!_blurMaterial)
        {
            _blurMaterial = new Material(BlurShader);
        }
        _screenLightCamera.backgroundColor = Color.gray;
        _screenLightCamera.enabled = false;
        _screenLightCamera.transform.localPosition = Vector3.zero;
        _screenLightCamera.transform.localRotation = Quaternion.identity;
        _screenLightCamera.transform.localScale = Vector3.one;

        _screenLightCamera.orthographicSize = camera.orthographicSize;
        _screenLightCamera.orthographic = camera.orthographic;        
    }

}